package routes

import (
	"context"
	"log"
	"myginproject/internal/controller"
	"myginproject/internal/controller/ws"
	"myginproject/internal/middleware"
	"myginproject/internal/models"
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func RegisterRoutes(r *gin.Engine, db *gorm.DB, hub *ws.Hub) {
	// 全局中间件
	r.Use(middleware.LoggerMiddleware())

	// 根路由
	r.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "欢迎使用群聊API服务",
			"usage": gin.H{
				"群聊WebSocket": "/ws/group?group_id=群ID&user_id=用户ID&name=用户名&avatar=头像URL",
				"注意":          "group_id可选(未提供会自动生成)，其他参数必填",
			},
		})
	})

	// 新增HTTP API路由
	apiGroup := r.Group("/api/v1/im")
	{
		apiGroup.POST("/send_group_msg", controller.SendGroupMessage(db, hub))
		apiGroup.POST("/add_group", controller.AddGroup(hub))
	}

	// 群聊WebSocket端点
	r.GET("/ws/group", func(c *gin.Context) {
		// 从URL获取参数
		groupID := c.Query("group_id")
		userID := c.Query("user_id")
		userName := c.Query("name")
		userAvatar := c.Query("avatar")

		// 验证必填参数
		if userID == "" || userName == "" {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error":   "缺少必要参数",
				"code":    400,
				"message": "必须提供user_id和name参数",
			})
			return
		}

		// 如果未提供group_id，自动生成一个
		if groupID == "" {
			// groupID = "group_" + strconv.FormatInt(time.Now().Unix(), 10)
			c.JSON(http.StatusInternalServerError, gin.H{
				"error":   "缺少必要参数",
				"code":    400,
				"message": "必须提供group_id参数",
			})
			return
		}

		// 检查群组是否存在
		ctx := context.Background()
		exists, err := hub.GetRedis().Exists(ctx, "WsGroup:"+groupID).Result()
		if err != nil {
			log.Printf("Redis查询错误: %v", err)
			c.JSON(http.StatusInternalServerError, gin.H{
				"error":   "服务器内部错误",
				"code":    500,
				"message": "无法验证群组状态",
			})
			return
		}

		if exists == 0 {
			log.Printf("拒绝连接: 群组 %s 不存在", groupID)
			c.JSON(http.StatusInternalServerError, gin.H{
				"status":  "error",
				"code":    4001, // 自定义错误码
				"message": "群组  不存在，请先创建",
			})
			return
		}

		// 创建用户对象
		user := &models.WsUser{
			ID:     userID,
			Name:   userName,
			Avatar: userAvatar,
		}

		// 升级为WebSocket连接
		conn, err := ws.Upgrader.Upgrade(c.Writer, c.Request, nil)
		if err != nil {
			log.Printf("WebSocket升级失败: %v", err)
			c.JSON(http.StatusInternalServerError, gin.H{
				"error":   "websocket错误",
				"code":    500,
				"message": "无法建立WebSocket连接",
			})
			return
		}

		// 处理群聊连接（使用正确的参数）
		hub.HandleGroupChat(conn, user, groupID)

		log.Printf("新WebSocket连接: 用户=%s (%s) 群组=%s", userID, userName, groupID)
	})

	// 保留原有的用户路由
	userController := &controller.UserController{}
	userGroup := r.Group("/users")
	{
		userGroup.GET("/:id", userController.GetUser)
		userGroup.GET("/", userController.CreateUser)
	}

	// 保留原有的产品路由
	productController := &controller.ProductController{}
	productGroup := r.Group("/products")
	{
		productGroup.GET("/:id", productController.GetProduct)
		productGroup.GET("/", productController.CreateProduct)
	}

	// 保留原有的华数对话路由
	HuashuController := controller.NewHuashuController(db)
	HuashuGroup := r.Group("/huashu")
	{
		HuashuGroup.GET("/search", HuashuController.SearchHuashu)
	}

	// 健康检查路由
	r.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"status": "ok"})
	})

	log.Println("所有路由注册完成")
}
